﻿using UnityEditor;
using UnityEngine;
using System.Collections;

[CustomEditor(typeof(PUEXOrbitAffector))]
public class PUEXOrbitAffectorEditor : Editor {

	public void OnSceneGUI ()
	{
		var affector = target as PUEXOrbitAffector;
		if (!affector.enabled)
			return;
		
		Matrix4x4 defaultMatrix = Handles.matrix;
		if (affector.inWorldSpace) {
			Handles.matrix = Matrix4x4.identity;
		} else {
			Handles.matrix = affector.transform.parent.transform.localToWorldMatrix;
		}
		
		Quaternion quat = Quaternion.LookRotation(affector.rotationAxis);
		
		if (Tools.current == Tool.Rotate) {
			quat = Handles.RotationHandle (quat, Vector3.zero);
			Vector3 value = quat * Vector3.forward;
			
			if (GUI.changed) {
				Undo.RecordObject(affector, "PUEXOrbitAffectorEditor Modify");
				affector.rotationAxis = value;
				EditorUtility.SetDirty(affector);
			}
		}

		Vector3 dir = affector.rotationAxis * HandleUtility.GetHandleSize (Vector3.zero);
		Handles.DrawLine (Vector3.zero - dir, Vector3.zero + dir);
		Handles.ConeCap(0, Vector3.zero + dir, quat, HandleUtility.GetHandleSize(Vector3.zero) * 0.2f);
		
		Handles.matrix = defaultMatrix;
	}

}
